import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.geojson.GeoJSONReader;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.type.FeatureTypeImpl;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.geometry.jts.Geometries;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import utilityTools.GeoJsonUtiles;

import java.io.*;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

//测试所有和geojson相关的内容
public class GeojsonOperation {
    //测试jsonarray的获取，什么情况下可以获取
    public void testGeojsonOpration() throws Exception {
        String path="E:\\9.1GISData\\geojson_point.json";
        String path2="E:\\9.1GISData\\geojson_polygon.json";
        File fileInput=new File(path);
        JSONObject geojsonSource= GeoJsonUtiles.getGeoJsonSource(fileInput);
        String ttt=geojsonSource.getString("Type");
//        JSONObject ssss= geojsonSource.getJSONObject("properties");//json对象必须一级一级的获取
        JSONArray array=geojsonSource.getJSONArray("features");
        for (Object tmp : array) {
            JSONObject tobj=(JSONObject) tmp;
//            JSONArray propArray= tobj.getJSONArray("properties");//不是每一个Json对象都可以使用getarray的方法
            //获取的array其实也是一系列Json对象的集合
//            for (Object prop : propArray) {
//                System.out.println(prop);
//            }
        }
    }

    public void testOpenGeojson() throws IOException {
        String fileGeojsonNoChildObj="E:\\gislogs\\testexp02.geojson";
        String fileGeojsonHasChildObj="E:\\gislogs\\demoProvince.geojson";
        String fileGeojson01="C:\\Users\\BB\\Desktop\\JLJ\\demo.geojson";
        boolean useOldMethod=false;
        if (useOldMethod) {
            FeatureJSON featureJSON = new FeatureJSON();
            SimpleFeatureType type1 = featureJSON.readFeatureCollectionSchema(
                    new FileInputStream(fileGeojsonHasChildObj), true);
            System.out.println(type1.getTypeName());
            FeatureCollection featureCollection = featureJSON.readFeatureCollection(new FileInputStream(fileGeojsonHasChildObj));
            SimpleFeatureType type = (SimpleFeatureType) featureCollection.getSchema();
            System.out.println(type.getTypeName());//feature
            System.out.println(type.getName().getLocalPart());
            System.out.println(type.getName().getURI());//GeoTools的网址
            System.out.println(featureCollection.getBounds().getMaxX());
        }else {
            File file = new File(fileGeojson01);
            Map<String, Serializable> map = new HashMap<>();
            map.put("url", file.toURI().toURL());
            DataStore dataStore = DataStoreFinder.getDataStore(map);
            String typeName=dataStore.getTypeNames()[0];//得到的是文件的名字;而不是图层的名称
            System.out.println("geojson的文件名："+typeName);
            //geojson情况下，如果直接从schema获取几何类型，只能得到geometry的类型
            SimpleFeatureType schema = dataStore.getSchema(typeName);
            System.out.println("几何类型名："+schema.getGeometryDescriptor().getType().getBinding().getTypeName());
            SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
            String typeName1 = featureSource.getSchema().getGeometryDescriptor().getType().getBinding().getTypeName();
            System.out.println("第二种方式获取几何类型名："+typeName1);
            //下面这一部分才会出问题；之前获取store和FeatureSource时都不会报错
            SimpleFeatureCollection featureCollection = featureSource.getFeatures();
            ReferencedEnvelope bounds = featureCollection.getBounds();
            SimpleFeatureIterator featureIterator = featureCollection.features();
            while (featureIterator.hasNext()) {
                SimpleFeature perFeature = featureIterator.next();
                System.out.println("第三种方式获取几何类型名："+perFeature.getDefaultGeometryProperty().getType().getBinding().getTypeName());
                System.out.println("第四种："+perFeature.getDefaultGeometryProperty().getType().getName());
                System.out.println(perFeature.getID());
            }
            //System.out.println("要素数量："+featureSource.getCount(null));//切换后，shp文件在这里也会报错
            System.out.println("maxX:"+bounds.getMaxX());
        }


    }
    public  void testError() throws IOException {
        String fileGeojsonNoChildObj="E:\\gislogs\\testexp.geojson";
        String fileGeojsonHasChildObj="E:\\gislogs\\demoProvince.geojson";
        String fileShp="E:\\gislogs\\shptest\\shpHasParent.shp";
        String fileShpNoP="E:\\gislogs\\shptest\\shpNoParent.shp";
        File gjFile=new File(fileGeojsonHasChildObj);
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(gjFile.toURI().toURL());
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode node = mapper.readTree(parser);
        JsonNode features = node.get("features");
        JsonNode props = features.get(0).get("properties");
        Iterator<Map.Entry<String, JsonNode>> fields = props.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> n = fields.next();
            JsonNode value = n.getValue();
            if (value instanceof ObjectNode) {
                //就没有type这个键，所以这里获取的是null，进而导致转换错误
                String type = value.get("type").asText();
                Geometries namedType = Geometries.getForName(type);

            }
        }
    }

    public void test验证并获取GeoJson字符串的几何() throws IOException {
        String valueInput="{\"type\":\"Polygon\",\"coordinates\":[[[107.16624082673702,33.09305585702302],[107.16451473910764,33.07837223142657],[107.15940280879909,33.064250577315875],[107.15110148442632,33.05123397964851],[107.1399297812295,33.039823253727604],[107.12631702149741,33.03045760859439],[107.11078633595235,33.02349766175994],[107.09393456013017,33.019211474240535],[107.07640929832507,33.01776415876693],[107.05888403651998,33.019211474240535],[107.04203226069778,33.02349766175994],[107.02650157515274,33.03045760859439],[107.01288881542062,33.039823253727604],[107.00171711222383,33.05123397964851],[106.99341578785106,33.064250577315875],[106.98830385754249,33.07837223142657],[106.98657776991311,33.09305585702302],[106.98830385754249,33.10773703055493],[106.99341578785106,33.12185170177731],[107.00171711222383,33.13485784881563],[107.01288881542062,33.146256247381935],[107.02650157515274,33.15560956516366],[107.04203226069778,33.16255906137656],[107.05888403651998,33.16683826601515],[107.07640929832507,33.168283129427316],[107.09393456013017,33.16683826601515],[107.11078633595235,33.16255906137656],[107.12631702149741,33.15560956516366],[107.1399297812295,33.146256247381935],[107.15110148442632,33.13485784881563],[107.15940280879909,33.12185170177731],[107.16451473910764,33.10773703055493],[107.16624082673702,33.09305585702302]]]}";
        JSONValidator jsonValidator = JSONValidator.from(valueInput);
        System.out.println(jsonValidator.getType());
        if (JSONValidator.from(valueInput).validate()) {
            GeometryJSON geoJSON = new GeometryJSON();
            Geometry geoInput = geoJSON.read(new StringReader(valueInput));
            System.out.println(geoInput.toText());
        }else {
            System.out.println("输入的GeoJson字符串错误，请检查!");
        }
    }

}
